#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <pthread.h>
int udp_recv(int sockfd, void *buf, int size, struct sockaddr_in *fromaddr)
{
	//接收数据
	socklen_t len = sizeof(struct sockaddr);
	int rsize = recvfrom(sockfd, buf, size, 0, (struct sockaddr*)fromaddr, &len);
	if(rsize < 0) 
	{
		perror("recvfrom fail");
	}
		printf("welcome: %s:%hu\n", 
			inet_ntoa((*fromaddr).sin_addr),
			ntohs((*fromaddr).sin_port));
		printf("%d\n",rsize);
	int ret = sendto(sockfd, &rsize, 4, 0, (struct sockaddr*)fromaddr, sizeof(struct sockaddr));
	if(ret < 0) return -1;
	else return rsize;
}



//接收端---创建套接字socket---绑定bind----接收数据recvfrom
int main(int argc, char **argv)
{
	//创建套接字
	int sockfd  = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0)
	{
		perror("socket fail");
		return -1;
	}

	//定义接收端要绑定的地址
	struct sockaddr_in saddr;//==struct sockaddr
	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(atoi(argv[1]));//atoi,argv[1], htons
	saddr.sin_addr.s_addr = htonl(INADDR_ANY); //--inet_addr("0.0.0.0")
	int ret = bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
	if(ret < 0)
	{
		perror("绑定失败");
		exit(1);
	}
	
	char recvbuf[1024]={0};
	struct sockaddr_in fromaddr;//存储发送端地址

	
	unsigned int filesize = 0;
	char filename[64];
	
	udp_recv(sockfd, recvbuf, 1024, &fromaddr);
	
	memcpy(&filesize, recvbuf, 4);
	strcpy(filename, recvbuf+4);

	FILE *file = fopen(filename, "w+");
	
	unsigned int recvsize = 0;


	while(1)
	{
		if(recvsize < filesize)
		{
		int rsize = udp_recv(sockfd, recvbuf, sizeof(recvbuf), &fromaddr);		
		/*printf("welcome: %s:%hu\n", 
			inet_ntoa(fromaddr.sin_addr),
			ntohs(fromaddr.sin_port));*/
		fwrite(recvbuf, rsize, 1, file);
		recvsize += rsize;
		//printf("recvsize =%d\n", recvsize);
		}
		else break;
	}

	fclose(file);
	
	return 0;
}
